package cc.yugu.yhdw.webserver.service.hdw;

import cc.yugu.yhdw.common.domain.hdw.*;
import cc.yugu.yhdw.common.entity.json.ExtResult;
import cc.yugu.yhdw.common.entity.pagination.Page;
import cc.yugu.yhdw.webserver.persistence.basic.SystemConfigMapper;
import cc.yugu.yhdw.webserver.persistence.hdw.*;
import cc.yugu.yhdw.webserver.service.AbstractService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
/**
 * 电池业务
 *
 * @Date:Created in 2018/7/5 17:49
 * @Author:
 * @Modified By: zjn 2018/7/5 17:49
 */
@Service
public class BatteryService extends AbstractService {
    @Autowired
    BatteryMapper batteryMapper;
    @Autowired
    CabinetBoxMapper cabinetBoxMapper;
    @Autowired
    BatteryPackMapper batteryPackMapper;
    @Autowired
    SystemConfigMapper systemConfigMapper;
    @Autowired
    UnregisterBatteryMapper unregisterBatteryMapper;
    // 新注入
    @Autowired
    BatteryAgentMapper batteryAgentMapper;
    /**
     * 表格刷新
     * @Param [battery]
     * @Return cc.yugu.yhdw.common.entity.pagination.Page
     * @Author zxj 2018/8/4
     * @Edit zxj 2018/8/20 add branch (abnormal battery）
     */
    public Page findPage(Battery battery) {
        Page page = battery.buildPage();
        /*
         电池管理表格刷新：业务重构（权限）
            (电池管理中的数据都是实时更新的）
            add abnormal battery
            异常电池(healthy为 2)
                1.电量低于10%；
                2.电量低于20%且超过两天（包含两天）未使用；
                3.温度高于65摄氏度
                4.电流大于25A
         */
        if (battery.getHealthy() != null && battery.getHealthy() == 2) {
            // 异常电池
            page.setTotalItems(batteryMapper.findPageCountByAbnormal(battery));
            battery.setBeginIndex(page.getOffset());
            List<Battery> batteryList = batteryMapper.findPageResultByAbnormal(battery);
            page.setResult(batteryList);
            return page;
        }
        page.setTotalItems(batteryMapper.findPageCounts(battery));
        battery.setBeginIndex(page.getOffset());
        List<Battery> batteryList = batteryMapper.findPageResults(battery);
        page.setResult(batteryList);


        /* // 循环费时间(可以优化)
        for (Battery e : batteryList) {
            //设置厂商名称
            e.setSupplierName(findSupplierInfo(e.getSupplierId()).getSupplierName());
        }*/
        return page;
    }
    /**
    * 根据客户id查询表hdw_battery中一条数据
    *
    * @Param: [id]
    * @Return: cc.yugu.yhdw.common.domain.hdw.Battery
    * @Author By: zjn 2018/7/5  17:51
    */
    public Battery findByCustomer(Integer id) {
        return batteryMapper.findByCustomer(id);
    }
    /**
    * 查询
    *
    * @Param: [id]
    * @Return: cc.yugu.yhdw.common.domain.hdw.Battery
    * @Author By: zjn 2018/7/5  17:51
    */
    public Battery find(String id) {
        // 根据主键查询
        Battery battery = batteryMapper.find(id);
        // 根据电池组id查询电池组信息
        BatteryPack batteryPack = batteryPackMapper.find(battery.getPackId());
        battery.setSupplierName(findSupplierInfo(batteryPack.getSupplierId()).getSupplierName());
        battery.setPackNo(batteryPack.getPackNo());
        return battery;
    }
    /**
    * 查询使用日志
    * 
    * @Param: [date, id]
    * @Return: java.util.List<java.lang.String>
    * @Author By: zjn 2018/7/5  17:57
    */ 
    public List<String> findUsageLog(Date date, String id) {
        if (date == null) {
            date = new Date();
        }
        List<String> list = batteryMapper.findUsageLog(date, id);
        return list;
    }
    /**
    * 根据旧电id或者新电id查询表 hdw_exchange_order中创建时间（按创建时间分组）
    * 
    * @Param: [id]
    * @Return: java.util.List<java.lang.String>
    * @Author By: zjn 2018/7/5  17:57
    */ 
    public List<String> findUsageLogCount(String id) {
        return batteryMapper.findUsageLogCount(id);
    }
    /**
    * 插入
    * 
    * @Param: [battery]
    * @Return: cc.yugu.yhdw.common.entity.json.ExtResult
    * @Author By: zjn 2018/7/5  17:59
    */ 
    public ExtResult insert(Battery battery) {
        if (batteryMapper.checkRepeat(battery) > 0) {
            return ExtResult.failResult("电池序号已存在不能重复添加");
        }
        battery.setExchangeAmount(0);
        battery.setStatus(Battery.Status.FREE.getValue());
        battery.setCreateTime(new Date());
        int total = batteryMapper.insert(battery);
        if (total == 0) {
            return ExtResult.failResult("添加失败");
        }
        return ExtResult.successResult();
    }
    /**
    * 新增：分别往hdw_battery表和hdw_battery_agent表中插入数据（新建电池时用）
    *
    * @Param: [battery, batteryAgent]
    * @Return: cc.yugu.yhdw.common.entity.json.ExtResult
    * @Author By: zjn 2018/7/26  14:28
    */
    public ExtResult insert(Battery battery,BatteryAgent batteryAgent) {
        if (batteryMapper.checkRepeat(battery) > 0) {
            return ExtResult.failResult("电池序号已存在不能重复添加");
        }
        batteryAgent.setBatteryId(battery.getId());
        if(batteryAgent!=null){
           int total1 = batteryAgentMapper.insert(batteryAgent);
           if (total1 == 0 ){
               return ExtResult.failResult("添加失败");
           }
        }
        battery.setExchangeAmount(0);
        battery.setStatus(Battery.Status.FREE.getValue());
        battery.setCreateTime(new Date());
        int total = batteryMapper.insert(battery);
        if (total == 0) {
            return ExtResult.failResult("添加失败");
        }
        return ExtResult.successResult();
    }
    /**
    * 注册电池
    * 
    * @Param: [battery]
    * @Return: cc.yugu.yhdw.common.entity.json.ExtResult
    * @Author By: zjn 2018/7/5  17:59
    */ 
    @Transactional(rollbackFor = Throwable.class)
    public ExtResult boundCard(Battery battery) {
        // 根据主键查询，返回行数>0
        if (batteryMapper.checkRepeat(battery) > 0) {
            return ExtResult.failResult("电池序号已存在不能重复添加");
        }
        // 设置电池使用次数为 0
        battery.setExchangeAmount(0);
        // 设置电池状态为 空闲
        battery.setStatus(Battery.Status.FREE.getValue());
        // 设置创建时间
        battery.setCreateTime(new Date());
        // 插入
        int total = batteryMapper.insert(battery);
        if (total == 0) {
            return ExtResult.failResult("添加失败");
        }
        // 若注册成功，则将未注册电池表中的该电池记录删掉
        unregisterBatteryMapper.delete(battery.getId());
        return ExtResult.successResult();
    }
    /**
    * 根据主键更新表hdw_battery外壳编号和电池组id
    * 
    * @Param: [battery]
    * @Return: cc.yugu.yhdw.common.entity.json.ExtResult
    * @Author By: zjn 2018/7/5  18:06
    */ 
    @Transactional(rollbackFor = Throwable.class)
    public ExtResult update(Battery battery) {
        int total = batteryMapper.update(battery);
        if (total == 0) {
            return ExtResult.failResult("添加失败");
        }
        return ExtResult.successResult();
    }
    /**
    * 新增方法: 更新两个表
    *
    * @Param: [battery, batteryAgent]
    * @Return: cc.yugu.yhdw.common.entity.json.ExtResult
    * @Author By: zjn 2018/7/26  16:11
    */
    @Transactional(rollbackFor = Throwable.class)
    public ExtResult updateAgent(Battery battery,BatteryAgent batteryAgent) {

        int total = batteryMapper.update(battery);
        if (total == 0) {
            return ExtResult.failResult("添加失败");
        }
        // 更新表hdw_battery_agent
        batteryAgent.setBatteryId(battery.getId());
        if (batteryAgentMapper.find(batteryAgent.getBatteryId())==null){
            int total2 = batteryAgentMapper.insert(batteryAgent);
            if (total2 == 0){
                return ExtResult.failResult("添加失败");
            }
        }else {
            int total3 = batteryAgentMapper.update(batteryAgent);
            if (total3 == 0) {
                return ExtResult.failResult("添加失败");
            }
        }
        return ExtResult.successResult();
    }
    /**
    * 根据主键删除记录
    * 
    * @Param: [id]
    * @Return: int
    * @Author By: zjn 2018/7/5  18:06
    */ 
    public int delete(String id) {
        return batteryMapper.delete(id);
    }
    /**
    * 查询电池的健康度，返回行数（healthy > 80）
    * 
    * @Param: []
    * @Return: int
    * @Author By: zjn 2018/7/5  18:09
    */ 
    public int findFault() {
        return batteryMapper.findFault();
    }
    /**
     * 故障电池（new 权限）
     * @Param [agentId, agencyId]
     * @Return int
     * @Author zxj 2018/8/3
     */
    public int findFaults(Integer agentId, Integer agencyId) {
        return batteryMapper.findFaults(agentId, agencyId);
    }
    /**
     * 查询异常电池数量
     * @Param [agentId, agencyId]
     * @Return int
     * @Author zxj 2018/8/21
     */
    public int findAbnormal(Integer agentId, Integer agencyId) {
        return batteryMapper.findAbnormal(agentId, agencyId);
    }
    /**
    * 查询经纬度
    * 电池分布图查询电池信息展示
    * @Param: []
    * @Return: java.util.List<java.util.Map<java.lang.String,java.lang.Double>>
    * @Author By: zjn 2018/7/5  18:10
     * @editer By: zxj 20180821 15:50 add field id,shellCode,status,socVolume,exchangeAmount
    */ 
    public List<Map<String, Double>> findAll() {
        // return batteryMapper.findAll();
        return batteryMapper.findAllToMap();
    }
}
